<template>
	<div class="tikuBg">

		<div class="banner">
			<image src="https://www.baixuemianshi.com/zhuanti/images/swiper_xcx2.jpg" mode="widthFix"></image>
		</div>
		<u-sticky bgColor="#fff">
			<u-tabs :list="lxList" :current="yjCurrent" @change="changeTabs"></u-tabs>
			<div v-if="ejlxList.length > 0" class="subFilter">
				<u-tabs :list="ejlxList" :current="ejCurrent" @change="changeEjTabs" lineColor="#f56c6c"></u-tabs>
			</div>
			<div v-if="sjlxList.length > 0" class="subFilter">
				<u-tabs :list="sjlxList" :current="sjCurrent" @change="changeSjTabs" lineColor="#f56c6c"></u-tabs>
			</div>
			<div class="searchBox">
				<u-search placeholder="输入关键字搜索" shape="round" v-model="searchVal" @search="searchFnc"
					@custom="searchFnc" @change="searchFnc"></u-search>
			</div>
			<div class="selectBanji">{{zutiTitle}}</div>
			<div class="taotiBox" v-if="banjiDetail && banjiDetail.type =='套题模式'">
				<div class="item" v-for="(item,index) in banjiDetail.info.tao" :key="index" @click="selectTao = index"
					:class="selectTao == index ? 'active' : ''">
					<h4>第{{index + 1}}套</h4>
					<ul>
						<li v-for="(i,j) in banjiDetail.info.ti" :key="j"
							:class="(j < timuDetail[index].length) ? 'cur': ''"></li>
					</ul>
				</div>
			</div>


		</u-sticky>
		<div class="loadBox" v-if="searchLoading">
			<u-loading-icon size="36" mode="circle" :vertical="true" color="red" text="加载中..."
				textSize="20"></u-loading-icon>
		</div>
		<div class="container">

			<div class="items" v-if="!searchVal">
				<div class="item" v-for="(item,index) in lists" :key="index" v-show="checkShow(item)">
					<h3>
						<u-parse :content="index + 1 + '、' + addGl(item.title)" :showImgMenu="false"
							:showMenu="false"></u-parse>
					</h3>
					<ul class="tags">
						<u-tag :text="item.leixing" plain size="mini" type="warning"></u-tag>
					</ul>

					<div class="btns">
<!-- v-if="item.answerDetail" -->
						<div class="btn" v-if="item.answerDetail">
							<u-button type="error" size="mini" text="查看逐字稿" @click="showAnswer(item)"></u-button>
						</div>
						<div class="btn" v-if="item.silu">
							<u-button type="error" size="mini" text="查看思路" @click="showAnswer(item)"></u-button>
						</div>
						<div class="btn" v-if="checkFav(item)">
							<u-button type="primary" size="mini" text="添加+" @click="addFav(item)"></u-button>
						</div>
						<div class="btn" v-else>
							<u-button type="primary" plain size="mini" text="取消+" @click="removeFav(item)"></u-button>
						</div>
					</div>
				</div>
				<div @click="loadMore">
					<u-loadmore :status="status" />
				</div>

			</div>
			<div class="items" v-else>
				<div class="item" v-for="(item,index) in searchList" :key="index" v-show="checkShow(item)">
					<h3>
						<u-parse :content="index + 1 + '、' + addGl(item.title)" :showImgMenu="false"
							:showMenu="false"></u-parse>
					</h3>
					<ul class="tags">
						<u-tag :text="item.leixing" plain size="mini" type="warning"></u-tag>
					</ul>

					<div class="btns">
						<!-- v-if="item.answerDetail" -->
						<div class="btn"  v-if="item.answerDetail">
							<u-button type="error" size="mini" text="查看逐字稿" @click="showAnswer(item)"></u-button>
						</div>
						<div class="btn" v-if="item.silu">
							<u-button type="error" size="mini" text="查看思路" @click="showAnswer(item)"></u-button>
						</div>
						<div class="btn" v-if="checkFav(item)">
							<u-button type="primary" size="mini" text="添加+" @click="addFav(item)"></u-button>
						</div>
						<div class="btn" v-else>
							<u-button type="primary" plain size="mini" text="取消+" @click="removeFav(item)"></u-button>
						</div>
					</div>
				</div>
			</div>

		</div>

		<div class="detailBtn">
			<div>
				<u-button type="primary" size="small" text="已选题目" @click="showDetail = true"></u-button>
			</div>
			<div>
				<u-button type="error" size="small" text="分享题目" open-type="share"></u-button>
			</div>
		</div>

		<div class="detailBox" style="z-index: 999;" v-if="showDetail">
			<div class="content">
				<h2>已选题目</h2>
				<div class="close" @click="showDetail = false"><u-icon name="close-circle" size="28"
						color="#000"></u-icon></div>
				<template v-if="banjiDetail.type=='刷题模式'">

					<div class="item" v-for="(item,index) in timuDetail" :key="index">
						<h3>
							<u-parse :content="(index + 1) + '、' + item.leixing + '-' + item.title"
								:showImgMenu="false"></u-parse>
						</h3>
						<div class="d_btns">
							<div class="btn"><u-button type="error" size="mini" text="删除"
									@click="removeFav(item)"></u-button></div>
							<div class="btn">
								<div v-if="!item.end">
									<u-button type="warning" size="mini" text="点击练完"
										@click="changeEnd(item,index)"></u-button>
								</div>
								<div v-else>
									<u-button type="warning" size="mini" plain text="已练完"
										@click="changeEnd(item,index)"></u-button>
								</div>
							</div>
							<div class="btn">
								<div v-if="!item.answer">
									
									<u-button type="success" size="mini" :text="item.status=='answerDetail'?'显示逐字稿':'显示思路'"
										@click="changeAnswer(item,index)"></u-button>
								</div>
								<div v-else>
									<u-button type="success" size="mini" plain :text="item.status=='answerDetail'?'隐藏逐字稿':'隐藏思路'"
										@click="changeAnswer(item,index)"></u-button>
								</div>
							</div>
							<div class="btn" ><u-button type="error" size="mini" :text="item.status=='answerDetail'?'查看逐字稿':'查看思路'"
									@click="showAnswer(item)"></u-button></div>
							<!-- <div class="btn" v-if="item.status=='silu'"><u-button  type="error" size="mini" text="查看思路"
										@click="showAnswer(item)"></u-button></div> -->
									
						</div>
	<button @click="savePageToImage(index,'lianxiti')" v-if="(index+1)%5==0 " style="margin-top: 20rpx;">保存页面为图片</button>
					</div>
					<!-- <canvas canvas-id="canvas" ></canvas> -->
					<button @click="savePageToImage(timuDetail.length-1)" v-if="timuDetail.length%5!=0" style="margin-top: 20rpx;">保存页面为图片</button>
				
				</template>

				<template v-else>
					<div class="item" v-for="(item,index) in timuDetail" :key="index">
						<h2>第（{{index + 1}}）套</h2>
						<div v-for="(list,j) in item" :key="j">
							<u-parse :content="(j + 1) + '、' + list.leixing + '-' + list.title"
								:showImgMenu="false"></u-parse>
							<div class="d_btns">
								<div class="btn"><u-button type="error" size="mini" text="删除"
										@click="removeFav(list,index)"></u-button></div>
								<div class="btn">
									<div v-if="!list.end">
										<u-button type="warning" size="mini" text="点击练完"
											@click="changeTaoTiEnd(index,j,list._id)"></u-button>
									</div>
									<div v-else>
										<u-button type="warning" size="mini" plain text="已练完"
											@click="changeTaoTiEnd(index,j,list._id)"></u-button>
									</div>
								</div>
								<div class="btn">
									<div v-if="!list.answer">
										<u-button type="success" size="mini" :text="list.status=='answerDetail'?'显示逐字稿':'显示思路'" 
											@click="changeTaoTiAnswer(index,j,list._id)"></u-button>
									</div>
									<div v-else>
										<u-button type="success" size="mini" plain :text="list.status=='answerDetail'?'隐藏逐字稿':'隐藏思路'"
											@click="changeTaoTiAnswer(index,j,list._id)"></u-button>
									</div>
								</div>
								<div class="btn" v-if="list.status=='silu'"><u-button type="error" size="mini" text="查看思路"
										@click="showAnswer(list)"></u-button></div>
								<div class="btn" v-else><u-button type="error" size="mini" text="查看逐字稿"
										@click="showAnswer(list)"></u-button></div>
										
						    	</div>
							<u-gap height="15" bgColor="#fff"></u-gap>
							<button @click="savePageToImage(index,'taoti',j,item)" v-if="(j+1)%5==0 && j+1 !== item.length"  style="margin-top: 20rpx;">保存页面为图片</button>
				    	<button @click="savePageToImage(index,'taoti',j,item)" v-if="j+1 == item.length" style="margin-top: 20rpx;">保存页面为图片</button>
						</div>

					</div>
				</template>

			</div>
		</div>

		<canvas canvas-id="waterMark" class="waterMark" style="width: 100vw; height: 100vh;"></canvas>
		<image :src="waterMarkUrl" class="waterMark-bg" style="width: 100vw; height: 100vh;"></image>
		<u-notify message="操作成功" :show="addSuccess"></u-notify>
			<canvas canvas-id="canvasimg"  class="canvasTu" v-if="detailBoxHeight>0" style="width: 280vw;z-index: 10;"
				:style="{height:detailBoxHeight+'rpx'}" id="canvasimg"></canvas>
	</div>
</template>

<script>
	import {
		mapActions
	} from 'vuex';
	const db = wx.cloud.database()
	export default {
		data() {
			return {
				detailBoxHeight: 0,
				waterMarkUrl: "",
				windowWidth: 100,
				windowHeight: 100,
				zutiTitle: "",
				banjiDetail: "",
				selectIndex: [],
				timuDetail: [],
				leixings: [],
				lxList: [],
				lists: [],
				yjCurrent: 1,
				filterLxName: "全部类型",
				ejlxList: [],
				filterErlx: "",
				ejCurrent: 1,

				sjlxList: [],
				filterSlx: "",
				sjCurrent: 1,

				searchVal: "",
				searchLoading: true,
				addSuccess: false,

				selectTao: 0,

				allSelect: [],

				showDetail: false,
				pages: 0,

				userinfo: "",

				status: "loadmore",
				loadEnd: false,

				searchList: [],
				textList: ['文本1', '文本2', '文本3'],
				canvasimgUrl: "",
				timuDraw:[],
				photoTitle:"",
				num:1,
				checkdata:[],
				bcTeacher:""
			}
		},
		onShareAppMessage(res) {
			if (res.from === 'button') { // 来自页面内分享按钮
				return {
					title: `题库-学员端`, //分享标题
					path: '/pages/nbhd/tiku/student', //分享页面路径
					imageUrl: 'https://www.baixuemianshi.com/zhuanti/tiku/images/xcx_share.jpg', //分享图标
					desc: '雪恒教育-白雪面试', //自定义分享描述 
				}
			} else {
				return {
					title: `题库-学员端`, //分享标题
					path: '/pages/nbhd/tiku/student', //分享页面路径
					imageUrl: 'https://www.baixuemianshi.com/zhuanti/tiku/images/xcx_share.jpg', //分享图标
					desc: '雪恒教育-白雪面试', //自定义分享描述 
				}
			}
		},
		onLoad(options) {
			this.zutiTitle = options.title
			console.log(options.title.split('-')[3], 'options.title')
			if(options.title.split('-')[3]=='刷题模式'){
				this.photoTitle='练习题'
			}else if(options.title.split('-')[3]=='套题模式'){
				this.photoTitle='模拟题'
			}
			this.getTimuInfo()
		},
		onShow() {
			// if(wx.setVisualEffectOnCapture){
			//     wx.setVisualEffectOnCapture({
			//         visualEffect: 'hidden',
			//         success:(res) => {
			//             console.log('success回调',res)
			//         },
			//     })
			// }
		},
		onHide() {
			// if(wx.setVisualEffectOnCapture){
			//     wx.setVisualEffectOnCapture({
			//         visualEffect: 'none',
			//         success:(res) => {
			//             console.log('success回调',res)
			//         },
			//     })
			// }
		},
		computed: {
			userphone() {
				return this.$store.getters.userphone ? this.$store.getters.userphone : '';
			},
			selectBanji() {
				return this.$store.getters.selectBanji ? this.$store.getters.selectBanji : '';
			},
			username() {
				return this.$store.getters.username ? this.$store.getters.username : '';
			},

		},
		created() {
			let that = this;

		},
		mounted() {
			let that = this

			wx.hideLoading()

			if (this.userphone) {
				this.drawWaterMark('雪恒教育-白雪面试 ' + this.userphone);
			} else {
				this.drawWaterMark('雪恒教育-白雪面试');
			}

		},
		
		onReachBottom() {
			if (this.loadEnd) {
				return
			}
			this.status = 'loading';
			this.pages = this.pages + 1;
			this.getList()
		},
		watch: {},
		methods: {
			...mapActions(['LogSetPhone', 'LogSetBanji']),
			paginate(array, page_size) {
			  let pages = [];
			  for (let i = 0; i < array.length; i += page_size) {
			    pages.push(array.slice(i, i + page_size));
			  }
			  return pages;
			},
			drawWaterMark(text) {
				this.getDeviceInfo().then(response => {
					const w = response.windowWidth;
					const h = response.windowHeight;
					this.windowWidth = w;
					this.windowHeight = h;
					//创建canvas绘制上下文
					const canvas = uni.createCanvasContext("waterMark", this);
					canvas.clearRect(0, 0, w, h)
					//开始创建一个路径，需要调用fill或者stroke才会使用路径进行填充或描边。
					canvas.beginPath();
					canvas.setFontSize(18);
					canvas.setFillStyle('rgba(0, 0, 0, 0.1)');
					canvas.rotate(-30 * Math.PI / 180)
					if (text) {
						text = this.trim(text)
					}
					const maxWidth = text.length * 18
					for (let x = 0; x < 10; x++) {
						for (let y = 0; y < 20; y++) {
							//在画布上绘制被填充的文本。
							canvas.fillText(text, (maxWidth + 40) * x - 400, 90 * y + 20);
						}
					}
					//将之前在绘图上下文中的描述（路径、变形、样式）画到 canvas 中。
					canvas.draw(false, () => {
						//把当前画布指定区域的内容导出生成指定大小的图片
						uni.canvasToTempFilePath({
							canvasId: "waterMark",
							complete: (res) => {
								this.waterMarkUrl = res.tempFilePath
							}
						}, this)
					})
				});
			},
			wrapText(ctx, text, maxWidth) {
				// 将文本按字符分割
				let words = text.split('');
				let lines = [];
				let currentLine = '';

				for (let i = 0; i < words.length; i++) {
					let testLine = currentLine + words[i];
					let metrics = ctx.measureText(testLine);
					let testWidth = metrics.width;
					if (testWidth > maxWidth && currentLine !== '') {
						lines.push(currentLine);
						currentLine = words[i];
					} else {
						currentLine = testLine;
					}
				}
				lines.push(currentLine);
				return lines;
			},
			savePageToImage(index,type,j,item) {
				console.log(11111)
				console.log(index,type,j,item,123)
				var that = this
				that.timuDraw =[]
				var indexs =index
				if(type =='taoti'){
					
					var newArr =that.paginate(item, 5)
					if(j+1 == item.length){
						that.timuDraw = newArr[newArr.length-1]
					}else{
						that.timuDraw = newArr[(j+1)/5-1]
					}
					
				}else{
					var newArr =that.paginate(this.timuDetail, 5)
					if(index+1 == that.timuDetail.length){
						that.timuDraw = newArr[newArr.length-1]
					}else{
						that.timuDraw = newArr[(index+1)/5-1]
					}
						
				}
				var dpr =null
				console.log(uni.getSystemInfoSync(),uni.getSystemInfoSync().deviceBrand , uni.getSystemInfoSync().deviceModel,uni.getSystemInfoSync().devicePixelRatio,'发给技术人员')
				if(uni.getSystemInfoSync().deviceBrand=="huawei" && uni.getSystemInfoSync().deviceModel=="ALN-AL00" ||uni.getSystemInfoSync().deviceBrand=="huawei" && uni.getSystemInfoSync().deviceModel=="ALN-AL80"){
					 dpr =3
				}else{
					 dpr = uni.getSystemInfoSync().devicePixelRatio;
				}
				console.log(dpr,'dpr')
				const query1 = uni.createSelectorQuery().in(this);
				query1.select('.detailBox').boundingClientRect((rect) => {
					if (rect) {
						this.detailBoxHeight = (this.timuDraw.length * 800) ;
							// that.detailBoxHeight = (rect.height +9 * 40) * dpr;
							
							console.log(rect.height,that.detailBoxHeight,'this.detailBoxHeightthat.detailBoxHeight',dpr)
					}
				}).exec();


				// setTimeout(() => {

					this.getDeviceInfo().then(response => {
						const w = response.windowWidth;
						const h = response.windowHeight;
						this.windowWidth = w;
						this.windowHeight = h;
						console.log(this.windowWidth,this.windowHeight,'this.windowWidththis.windowHeight')
						//创建canvas绘制上下文
						const canvas = uni.createCanvasContext("canvasimg", this);
						const query = uni.createSelectorQuery().in(this);
						query
							.select('#canvasimg')
							.fields({
								node: true,
								size: true
							})
							.exec((res) => {
							
								if (res && res[0]) {

									const canvas = res[0].node;
								}

							});




						//开始创建一个路径，需要调用fill或者stroke才会使用路径进行填充或描边。
						canvas.beginPath();
						canvas.setFontSize(28);
						canvas.setFillStyle('white');
						let height1 = that.detailBoxHeight > 0 ? that.detailBoxHeight * dpr : h;
						console.log(this.windowWidth,height1,that.detailBoxHeight,that.detailBoxHeight * dpr , h,'height1')
						canvas.fillRect(0, 0, this.windowWidth * dpr, height1)  //10.11 1030修改成this.windowWidth
						let imgurl = "https://www.baixuemianshi.com/zhuanti/paikeTeacher/images/background3.jpg";
						uni.getImageInfo({
							src: imgurl,
							success: (res) => {
								let canvasWidth = this.windowWidth * dpr;  //10.11 1030修改成this.windowWidth
								let canvasHeight = 1446;
								const imgWidth = res.width;
								const imgHeight = res.height;

								for (let x = 0; x < canvasWidth; x += imgWidth) {
									for (let y = 0; y < canvasHeight; y += imgHeight) {
											canvas.drawImage(res.path, x, y, imgWidth, imgHeight);
									}
								}
								// canvas.drawImage(res.path,0,0,300 * dpr, h)
								canvas.setFillStyle('black');
 
								const heightPerItem = 180; // 每段文本的间距
								let index1 = 0;
								// var json={leixing:'                                                             ',title:'测试'}
								// this.timuDraw.unshift(json)
							
								this.timuDraw.forEach((text, index) => {
									let formattedText =''
									// if(index ==0){
									// 	 formattedText =  text.leixing + text.title;
									// }else{
										 formattedText = (index+1) +  '、'  +text.title;
									// }
									// let formattedText = (index) + '、' + text.leixing + '-' +text.title;
									console.log(this.windowWidth,dpr,this.windowWidth*dpr-100,'文字换行的宽')
									let wrappedText = this.wrapText(canvas,formattedText,  this.windowWidth*dpr-100  ); //10.11 1030修改成this.windowWidth*dpr-100 // this.windowWidth*dpr-100   20 是左右边距
									wrappedText.forEach((line, lineIndex) => {
										index1++;
										// console.log( (index *heightPerItem),(index1 * 50)+100,'index1')
										// if (lineIndex) {
										// 	canvas.fillText(line, 10, (index *heightPerItem) +(index1 * 20));
										// } else {
											// console.log((index *heightPerItem) +(index1 * 50)+100,123)
											// 每道题之间的距离   50是文本换行的距离
											
											//10.11 1030修改成
											canvas.fillText(line, 10, (index *heightPerItem) +(index1 * 50)+70,this.windowWidth* dpr);  //+80 是距离标题的距离
										// }
									});

									// canvas.fillText((index + 1) + '、' + text.leixing + '-' + text.title, 10, index *
									// 	heightPerItem);
								});
								if(type =='taoti'){
									var num = index+1
									var title = ''
									title=this.photoTitle+'(第'+num+'套)'+this.zutiTitle
									canvas.fillText(title,80, 70, 800,30);
								}else{
				   					// canvas.setFontSize(32);
									canvas.setFillStyle();
									canvas.fillText(this.photoTitle,400, 70, 200,30);
								}
									
								//将之前在绘图上下文中的描述（路径、变形、样式）画到 canvas 中。
								canvas.draw(false, () => {  
									//把当前画布指定区域的内容导出生成指   定大小的图片
									uni.canvasToTempFilePath({
										canvasId: "canvasimg",
										complete: (res) => {
											this.canvasimgUrl = res
												.tempFilePath
											const tempFilePath = res
												.tempFilePath;
											uni.saveImageToPhotosAlbum({
												filePath: tempFilePath,
												success: () => {
													console.log(	this.timuDraw ,  this.timuDetail)
													this.detailBoxHeight =
														0;
													uni.showToast({
														title: '保存成功'
													});
													that.addmessage()
												},
												fail: () => {
													console.log(	this.timuDraw ,  this.timuDetail)
													uni.showToast({
														title: '保存失败',
														icon: 'none'
													});
												}
											});
										}
									}, this)
								})

							},
							fail: (err) => {}
						});

						//canvas.fillRect(0, 0, 300 * dpr, h)

					});
				// }, 500);

			},
			getTime(){
				let that = this
				let day = new Date()
				let y = day.getFullYear()
				let m = (day.getMonth() + 1).toString().padStart(2, '0');
				let d = day.getDate().toString().padStart(2, '0');
				let hour = day.getHours().toString().padStart(2, '0');
				let miu = day.getMinutes().toString().padStart(2, '0');
				let time = y + '-' + m + '-' + d + ' ' + hour + ':' + miu
				return time
			},
			addmessage(){
				// 手机号 班级 保存相册时间 去创建题库中查询 当前班级和手机号 对应的哪位老师
				
				// 思路 先查询表中是否有手机号 如果有 获取到id 修改 数量和操作的数组
				// 如果没有就创建 一条 bcxc_list
				console.log(this.timuDraw,"this.timuDraw")
				this.timuDraw.map(item=>{
					
				})
				let that = this
				that.checkdata =[]
				db.collection('bcxc_list').where({
					phone: that.userphone, 
				}).get({
					success: function(res) {
						console.log(res.data[0],res.data.length,'res.data.length')
					
						if (res.data.length !== 0) {
							that.checkdata = res.data[0].datalist
							var json ={
								time: that.getTime(),
								banji: that.$store.getters.selectBanji,
								timuDraw:that.timuDraw,
								length:that.timuDraw.length
							}
							that.checkdata.push(json)
							that.num =  res.data[0].num+1
							db.collection('bcxc_list').doc(res.data[0]._id).update({
								data: {
									phone: that.userphone,
									num: that.num,
									datalist:that.checkdata,
									length:that.timuDraw.length
								},
								success: res => {
									
								}
							})
						}else{
							
							// db.collection('nbhd_tiku_banjilist').where({
							// 	phone: that.userphone,
							// }).get({
							// 	success: function(res) {
							// 		console.log(res.data[0].teacher,'res.data6666')
							// 		that.bcTeacher = res.data[0].teacher
							
									var json ={
										time: new Date(),
										banji: that.$store.getters.selectBanji,
										timuDraw:that.timuDraw,
										length:that.timuDraw.length
									}
									that.checkdata.push(json)
									db.collection('bcxc_list').add({
										data: {
											phone: that.userphone,
											num: 1,
											datalist:that.checkdata,
											bcTeacher:that.username,
											length:that.timuDraw.length
										},
										success: function(res) {
											// that.showToast('success', '登录成功')
										},
										complete: function(req) {
											
										},
									})
							// 	}
							// })	
							
						
						}
					}
				})
				
			},
			updataBcxc(id,num){
				
			},
			addBcxc(){
				console.log("add")
				let that = this
				
				
			},
			trim(str) {
				let trimStr = '';
				const reg = /[\t\r\f\n\s]*/g;
				if (typeof str === 'string') {
					trimStr = str.replace(reg, '');
				}
				return trimStr
			},
			/**
			 * 获取当前设备的信息
			 * **/
			getDeviceInfo() {
				return new Promise((resolve, reject) => {
					uni.getSystemInfo({
						success: (sysInfo) => {
							resolve(sysInfo)
						}
					})
				})
			},
			getuserStatus() {
				let that = this
				db.collection('nbhd_tiku_banjilist').where({
					phone: that.userphone,
					banji: that.selectBanji
				}).get({
					success: function(res) {
						if (res.data.length > 0) {
							that.userinfo = res.data
							that.getLeixing()
						}
					}
				})
			},
			getTimuInfo() {
				let that = this
				db.collection('nbhd_n_tiku_tmList').where({
					banji: that.selectBanji,
					zTitle: that.zutiTitle
				}).get({
					success: function(res) {

						if (res.data.length > 0) {
							that.banjiDetail = res.data[0]
							that.timuDetail = res.data[0].list
							console.log(that.timuDetail,'that.timuDetail')
							that.getAllSelect(0)

						}
					}
				})

				// db.collection('nbhd_tiku_banji').where({
				// 	banji: that.selectBanji
				// }).get({
				// 	success: function(res) {
				// 		if(res.data.length > 0){
				// 			that.banjiDetail = res.data[0]
				// 			res.data[0].zuti.map((item,index) => {
				// 				if(item.title == that.zutiTitle){
				// 					that.selectIndex = index
				// 				}
				// 			})
				// 			that.timuDetail = res.data[0].zuti.filter(item => item.title == that.zutiTitle)[0]
				// 			that.getAllSelect()
				// 			that.getuserStatus()
				// 		}
				// 	}
				// })
			},
			getAllSelect(page) {
				let that = this
				let allArr = []

				wx.cloud.callFunction({
					name: 'get_page_banji',
					data: {
						fncname: 'nbhd_tiku_allselect_single',
						banji: that.selectBanji,
						page: page,
						limit: 100
					},
					complete: res => {
						if (res.result.data.length > 0) {
							that.allSelect = that.allSelect.concat(res.result.data)
							let p = page + 1
							that.getAllSelect(p)
						} else {
							that.getuserStatus()
						}

					}
				})
			},
			getList() {
				let that = this
				// that.searchLoading = true
				if (that.filterSlx) {
					wx.cloud.callFunction({
						name: 'get_chanyan_list',
						data: {
							type: that.filterLxName,
							leixing: that.filterErlx,
							leixing2: that.filterSlx,
							page: that.pages
						},
						complete: res => {
							if (res.result.data.length > 0) {
								that.lists = that.lists.concat(res.result.data)
							} else {
								that.loadEnd = true
								that.status = 'nomore'
							}
							that.searchLoading = false
						}
					})
				} else {

					wx.cloud.callFunction({
						name: 'get_chanyan_list',
						data: {
							type: that.filterLxName,
							leixing: that.filterErlx,
							page: that.pages
						},
						complete: res => {
							if (res.result.data.length > 0) {
								that.lists = that.lists.concat(res.result.data)
								// that.pages += 1
								// that.getList()
							} else {
								that.loadEnd = true
								that.status = 'nomore'
							}
							that.searchLoading = false
						}
					})
				}

			},
			getLeixing() {
				let that = this
				db.collection('nbhd_chanyan_lxs').where({
					kaoshi: that.userinfo[0].limit
				}).get({
					success: function(res) {
						that.leixings = res.data[0].lxList
						that.filterLx()
					}
				})
				// if(that.userinfo[0].limit == '全部'){
				// 	db.collection('nbhd_chanyan_lxs').doc("7027b654659c95de063b5c245b317d9a").get().then(res => {
				// 		that.leixings = res.data.lxList
				// 		that.filterLx()
				// 	})
				// }else if(that.userinfo[0].limit == '联考'){
				// 	db.collection('nbhd_chanyan_lxs').doc("0b153f9a6594b720058c8bec1e411fd5").get().then(res => {
				// 		that.leixings = res.data.lxList
				// 		that.filterLx()
				// 	})
				// }else{
				// 	db.collection('nbhd_chanyan_lxs').doc("a3df94cc6641731100babf5858efb6c0").get().then(res => {
				// 		that.leixings = res.data.lxList
				// 		that.filterLx()
				// 	})
				// }

			},
			filterLx() {
				let that = this
				let lxs = that.leixings.map(item => item.type)
				// lxs.unshift('全部类型')
				let lxNames = []
				lxs.map(item => {
					lxNames.push({
						"name": item
					})
				})
				that.lxList = lxNames
				that.yjCurrent = 0
				that.filterLxName = lxs[0]
				that.filterEjLx()
			},
			filterEjLx() {
				let that = this
				let ejList = that.leixings[that.yjCurrent].lxs
				let ejlxNames = []
				ejList.map(item => {
					ejlxNames.push({
						"name": item.title
					})
				})
				that.ejlxList = ejlxNames.length > 0 ? ejlxNames : []
				that.ejCurrent = 0
				that.filterErlx = that.ejlxList[0].name

				that.filterSjlx()
			},
			filterSjlx() {
				let that = this
				let ejList = that.leixings[that.yjCurrent].lxs
				let sjList = ejList.filter(item => item.title == that.filterErlx)
				let sjlxNames = []
				sjList[0].lxs2.map(item => {
					sjlxNames.push({
						"name": item
					})
				})
				that.sjlxList = sjlxNames.length > 0 ? sjlxNames : []
				that.sjCurrent = 0
				if (sjlxNames.length > 0) {
					that.filterSlx = that.sjlxList[0].name
				} else {
					that.filterSlx = ''
				}
				that.getList()

				wx.hideLoading()
			},
			changeTabs(e) {
				this.loadEnd = false
				this.status = 'loadmore'
				this.searchVal = ''
				this.yjCurrent = e.index
				this.filterLxName = e.name
				this.searchLoading = true
				this.lists = []
				this.pages = 0
				this.filterEjLx()
			},
			changeEjTabs(e) {
				this.loadEnd = false
				this.status = 'loadmore'
				this.searchVal = ''
				this.ejCurrent = e.index
				this.filterErlx = e.name
				this.searchLoading = true
				this.lists = []
				this.pages = 0
				this.filterSjlx()
			},
			changeSjTabs(e) {
				this.loadEnd = false
				this.status = 'loadmore'
				this.searchVal = ''
				this.sjCurrent = e.index
				this.filterSlx = e.name
				this.searchLoading = true
				this.lists = []
				this.pages = 0
				this.getList()
			},
			checkFav(item) {
				let that = this
				let idList = that.allSelect
				let iList = idList.map(info => info._id)
				let c = iList.includes(item._id)
				return !c


			},
			addFav(item) {
				let that = this
				that.searchLoading = true
				// item.answerDetail  item.silu
				var status=""
				if(item.answerDetail){
					status = 'answerDetail'
				}else if(item.silu){
					status = 'silu'
				}else{
					status = ''
				}
				let obj = {
					_id: item._id,
					leixing: item.leixing,
					title: item.title,
					end: false,
					answer: false,
					time: that.getTime(),
					zTitle: that.zutiTitle,
					status:status
				}
				if (that.banjiDetail.type == '刷题模式') {
					that.timuDetail.push(obj)
				} else {
					if (that.timuDetail[that.selectTao].length >= that.banjiDetail.info.ti) {
						uni.showToast({
							title: "最多" + that.banjiDetail.info.ti + '道题',
							icon: 'error'
						})
						that.searchLoading = false
						return
					}
					that.timuDetail[that.selectTao].push(obj)
				}
				db.collection('nbhd_n_tiku_tmList').doc(that.banjiDetail._id).update({
					data: {
						list: that.timuDetail
					},
					success: res => {
						that.addAllSelect(obj)
					}
				})

			},
			removeFav(obj, index) {
				let that = this
				that.searchLoading = true
				console.log(obj)
				if (that.banjiDetail.type == '刷题模式') {
					that.timuDetail = that.timuDetail.filter(item => item._id != obj._id);
				} else {
					that.timuDetail[index] = that.timuDetail[index].filter(item => item._id != obj._id);
				}
				db.collection('nbhd_n_tiku_tmList').doc(that.banjiDetail._id).update({
					data: {
						list: that.timuDetail
					},
					success: res => {
						that.removeAllSelect(obj._id)
					}
				})

			},
			addAllSelect(obj) {
				let that = this
				let nObj = {
					banji: that.selectBanji,
					zTitle: that.zutiTitle,
					tId: obj._id
				}
				db.collection('nbhd_tiku_allselect_single').add({
					data: nObj,
					success: function(res) {
						that.allSelect.push(nObj)
						that.searchLoading = false
					}
				})
			},
			removeAllSelect(id) {
				let that = this
				db.collection('nbhd_tiku_allselect_single').where({
					banji: that.selectBanji,
					tId: id
				}).remove()
				that.allSelect = that.allSelect.filter(item => item.tId != id)
				that.searchLoading = false
			},
			addGl(title) {
				let that = this
				if (!that.searchVal) {
					return title
				}
				let sText = title
				let sKey = "<span class='searchBg'>" + that.searchVal + "</span>"
				let num = -1,
					rStr = new RegExp(that.searchVal, "g"),
					rHtml = new RegExp("\<.*?\>", "ig"), //匹配html元素
					aHtml = sText.match(rHtml); //存放html元素的数组
				sText = sText.replace(rHtml, '{~}'); //替换html标签
				sText = sText.replace(rStr, sKey); //替换key
				sText = sText.replace(/{~}/g, function() {
					num++;
					return aHtml[num];
				});
				return sText
			},
			getTime() {
				let that = this
				let day = new Date()
				let y = day.getFullYear()
				let m = (day.getMonth() + 1).toString().padStart(2, '0');
				let d = day.getDate().toString().padStart(2, '0');
				let hour = day.getHours().toString().padStart(2, '0');
				let miu = day.getMinutes().toString().padStart(2, '0');
				let time = y + '-' + m + '-' + d + ' ' + hour + ':' + miu
				return time
			},
			checkShow(info) {
				let that = this
				let allId = that.allSelect.map(item => item.tId)
				let i = allId.indexOf(info._id)
				return i != -1 ? false : true
			},
			changeAnswer(info, index) {
				let that = this
				that.searchLoading = true
				that.timuDetail[index].answer = !that.timuDetail[index].answer
				db.collection('nbhd_n_tiku_tmList').doc(that.banjiDetail._id).update({
					data: {
						list: that.timuDetail
					},
					success: res => {
						that.searchLoading = false
					}
				})
			},
			async changeTaoTiAnswer(index, j, id) {
				let that = this
				that.searchLoading = true
				that.timuDetail[index][j].answer = !that.timuDetail[index][j].answer
				db.collection('nbhd_n_tiku_tmList').doc(that.banjiDetail._id).update({
					data: {
						list: that.timuDetail
					},
					success: res => {
						that.searchLoading = false
					}
				})

			},
			async changeTaoTiEnd(index, j, id) {
				let that = this
				that.searchLoading = true
				that.timuDetail[index][j].end = !that.timuDetail[index][j].end
				db.collection('nbhd_n_tiku_tmList').doc(that.banjiDetail._id).update({
					data: {
						list: that.timuDetail
					},
					success: res => {
						that.searchLoading = false
					}
				})
			},
			async changeEnd(info, index) {
				let that = this
				that.searchLoading = true
				that.timuDetail[index].end = !that.timuDetail[index].end
				db.collection('nbhd_n_tiku_tmList').doc(that.banjiDetail._id).update({
					data: {
						list: that.timuDetail
					},
					success: res => {
						that.searchLoading = false
					}
				})

			},
			showAnswer(item) {
				let that = this
				uni.navigateTo({
					url: "./answer?tmid=" + item._id
				})
			},
			searchFnc() {
				let that = this
				that.searchList = []
				if (that.filterSlx) {
					wx.cloud.callFunction({
						name: 'searchData',
						data: {
							type: that.filterLxName,
							leixing: that.filterErlx,
							leixing2: that.filterSlx,
							keyword: that.searchVal
						},
						complete: res => {
							if (res.result.length > 0) {
								that.searchList = that.searchList.concat(res.result)
							}
							that.searchLoading = false
						}
					})
				} else {
					wx.cloud.callFunction({
						name: 'searchData',
						data: {
							type: that.filterLxName,
							leixing: that.filterErlx,
							keyword: that.searchVal
						},
						complete: res => {
							if (res.result.length > 0) {
								that.searchList = that.searchList.concat(res.result)
							}
							that.searchLoading = false
						}
					})
				}

			},
			loadMore() {
				if (this.loadEnd) {
					return
				}
				this.status = 'loading';
				this.pages = this.pages + 1;
				this.getList()
			}
		},
		components: {

		}
	};
</script>

<style scoped>
	@import url(./index.css);

	.taotiBox {
		display: flex;
		padding: 25rpx;
	}

	.taotiBox .item {
		padding: 10rpx;
		border: 1px solid #ccc;
		border-radius: 10rpx;
		margin: 0 10rpx;
		flex: 1;
	}

	.taotiBox .item.active {
		border-color: #f00;
	}

	.taotiBox .item h4 {
		font-size: 28rpx;
		font-weight: bold;
		margin-bottom: 10rpx;
	}

	.taotiBox .item ul {
		display: flex;
		flex-wrap: wrap;
	}

	.taotiBox .item ul li {
		width: 10px;
		height: 10px;
		margin: 0 5rpx;
		border: 1px solid #ccc;
	}

	.taotiBox .item ul li.cur {
		background-color: #f00;
	}

	.selectBanji {
		font-size: 26rpx;
		padding: 15rpx 0;
		width: 700rpx;
		margin: 0 auto;
	}
</style>